package top.vains.config.shiro;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import top.vains.util.ResultUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * 通过此过滤器得到HTTP请求资源的authorization穿过来的token参数获取subject对象进行身份验证
 *
 * @author vains
 * @version 1.0
 * @since 2020/2/18 15:53
 **/
@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {

    /**
     * 应用的HTTP方法列表配置基本身份验证筛选器
     * 获取request请求，拒绝拦截登陆请求
     *
     * @param request 请求
     * @param response 响应
     * @param mappedValue 暂时未知
     * @return 返回布尔值
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        String uri = servletRequest.getRequestURI();
        String loginUri = "/login/verifyUser";
        if (Objects.equals(uri, loginUri)
            || Objects.equals(uri, "/login/register")) {
            return true;
        } else {
            try {
                return executeLogin(request, response);
            } catch (Exception e) {
                log.error("token验证失败", e);
                return false;
            }
        }
    }

    /**
     * authorization携带的参数为token
     * JwtToken封装了token参数
     * 通过getSubject()方法获取subject对象
     * login()方法发起登陆验证
     *
     * 为什么需要在过滤器中调用login方法而不再Controller中调用？
     * 由于shiro默认的验证方式时基于session的，在基于token的验证方式中，
     * 不能依赖session作为登陆的判断依据
     *
     * @param request 请求
     * @param response 响应
     * @return 返回布尔值
     * @throws Exception 抛出跟异常
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        try {
            String token = servletRequest.getHeader("Authorization");
            JwtToken jwtToken = new JwtToken(token);
            Subject subject = getSubject(request, response);
            subject.login(jwtToken);
            log.info("jwtToken验证通过");
            return true;
        } catch (Exception e) {
            log.error("jwt验证失败，失败原因：", e);
            /*
             * 在这里抛出异常时，不能被全局异常捕获
             * 推测时因为请求这时还没有到达Controller中
             * 需要在这里自定义响应信息
             */
            PrintWriter printWriter = servletResponse.getWriter();
            printWriter.println(new ObjectMapper().writeValueAsString(ResultUtils.error("token valid, please get it again!")));
            printWriter.flush();
            return false;
        }
    }

    /**
     * 添加跨域支持
     * @param request 请求
     * @param response 响应
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        servletResponse.setHeader("Access-control-Allow-Origin", servletRequest.getHeader("Origin"));
        servletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        servletResponse.setHeader("Access-Control-Allow-Headers", servletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里直接返回正常状态
        if (servletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            servletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }
}
